﻿#region  
//=====================================================
// 文件名: DownAssetBundle                
// 创建者: #AuthorName#                
// 创建时间: #CreateTime#              	
// Email: #AuthorEmail#               
// 描述: 当前脚本的功能              
// 修改者列表: 修改者名字以及修改功能      
// 版权所有: #Copyright#                 
//======================================================
#endregion 



using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using FrameWork;
using UnityEngine.UI;

public class DownAssetBundle : MonoBehaviour
{


    public Dictionary<string, bool> AllABPackage = new Dictionary<string, bool>();

    //此步骤需要自己搭建服务器  自己使用的是node搭建简单的本地服务
    private void Awake()
    {
        StartCoroutine(downAB("config", LoadAssetBundleConfig));
    }
    private void LoadAssetBundleConfig(string filename)
    {
        AssetBundleManager.Instance.LoadAssetBundleConfig();
        StartCoroutine(downAB("picture", ResponseDownABPacage));
    }

    private void ResponseDownABPacage(string AbName)
    {
        Sprite sprite = ResourceManager.Instance.LoadResource<Sprite>("Assets/GameMain/Picture/cat.jpg");
        GameObject.Find("Image").GetComponent<Image>().sprite = sprite;
        Debug.LogError("已加载进来"+ AbName);
    }

    IEnumerator downAB(string fileName,Action<string> action)
    {
        UnityWebRequest www = UnityWebRequest.Get("http://192.168.1.15:8000/"+ fileName);
        yield return www.SendWebRequest();
        if (www.isHttpError || www.isNetworkError)
        {
            Debug.LogError("下载出错了"+www.error);
        }
        else
        {
            byte[] by = www.downloadHandler.data;
            Debug.LogError("下载成功："+ fileName);
            if (Directory.Exists(Application.streamingAssetsPath))
            {
                CreateModelFile(Application.streamingAssetsPath, fileName, by, by.Length);
                action?.Invoke(fileName);
            }
        }
    }
    void CreateModelFile(string path, string name, byte[] info, int length)
    {
        Stream sw;
        FileInfo t = new FileInfo(path + "//" + name);
        if (!t.Exists)
        {
            //如果此文件不存在则创建
            sw = t.Create();
        }
        else
        {
            //如果此文件存在则打开
            //sw = t.Append();
            return;
        }
        //以行的形式写入信息
        //sw.WriteLine(info);
        sw.Write(info, 0, length);
        //关闭流
        sw.Close();
        //销毁流
        sw.Dispose();
    }
}
